package cn.hamster3.hamsterworld.command;

import cn.hamster3.hamsterworld.core.DataManager;
import cn.hamster3.hamsterworld.core.Message;
import cn.hamster3.hamsterworld.data.WorldData;
import org.bukkit.Bukkit;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@SuppressWarnings("deprecation")
public class RemoveCommand extends CommandBase {
    public RemoveCommand(DataManager dataManager) {
        super(dataManager);
    }

    @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        Player player = (Player) sender;
        WorldData worldData = dataManager.getWorldData(player);
        if (worldData == null) {
            player.sendMessage(Message.notHasWorld.toString());
            return true;
        }
        if (args.length < 2) {
            player.sendMessage(Message.notInputPlayerName.toString());
            return true;
        }
        if (player.getName().equalsIgnoreCase(args[1])) {
            player.sendMessage(Message.cantRemoveSelf.toString());
            return true;
        }
        OfflinePlayer offlinePlayer = Bukkit.getOfflinePlayer(args[1]);
        if (offlinePlayer == null) {
            player.sendMessage(Message.playerNotExist.toString());
            return true;
        }
        worldData.disallowPlayer(offlinePlayer.getUniqueId());
        for (Player worldPlayer : worldData.getWorld().getPlayers()) {
            if (!worldPlayer.getUniqueId().equals(offlinePlayer.getUniqueId())) {
                continue;
            }
            worldPlayer.teleport(Bukkit.getWorlds().get(0).getSpawnLocation());
            worldPlayer.sendMessage(Message.kickPlayer.toString().replace("%player%", sender.getName()));
        }
        player.sendMessage(Message.removeSuccess.toString().replace("%player%", offlinePlayer.getName()));
        return true;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        Player player = (Player) sender;
        ArrayList<String> tab = new ArrayList<>();
        WorldData worldData = dataManager.getWorldData(player);
        if (worldData == null) {
            return tab;
        }

        for (UUID uuid : worldData.getAllowedPlayer()) {
            String playerName = Bukkit.getOfflinePlayer(uuid).getName();
            if (!playerName.toLowerCase().startsWith(args[1].toLowerCase())) {
                continue;
            }
            tab.add(playerName);
        }
        return tab;
    }
}
